<template>
<!-- 添加或修改岗位对话框 -->
    <el-dialog v-model="open" :title="form.productId?'修改数据':'新增数据'" width="500px" append-to-body >
        <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="商品名" label-width="100" prop="productName">
                <el-input v-model="form.productName" placeholder="请输入商品名" />
            </el-form-item>

            <el-form-item label="类别" prop="superId">
                <el-input v-model="form.superId" placeholder="请输入商品类别" />
            </el-form-item>

             <el-form-item label="是否包邮" label-width="100" prop="freeNot">
                <el-input v-model="form.freeNot" placeholder="是否包邮0/1" />
            </el-form-item>

            <el-form-item label="是否售卖" label-width="100" prop="saleNot">
                <el-input v-model="form.saleNot" placeholder="是否售卖0/1" />
            </el-form-item>

            <el-form-item label="商品价格" label-width="100" prop="productPrice">
                <el-input v-model="form.productPrice" placeholder="请输入商品价格" />
            </el-form-item>

            <el-form-item label="商品描述" label-width="100" prop="detail">
                <el-input v-model="form.detail" placeholder="请输入商品描述" />
            </el-form-item>

            <el-form-item label="是否打折" label-width="100" prop="isDiscount">
                <el-input v-model="form.isDiscount" placeholder="是否打折0/1" />
            </el-form-item>

            <el-form-item label="是否允许积分兑换" label-width="100" prop="isCreditsExchange">
                <el-input v-model="form.isCreditsExchange" placeholder="是否允许积分兑换0/1" />
            </el-form-item>



            <el-form-item label="商品运费模板" label-width="100" prop="templateId">
                <el-input v-model="form.templateId" placeholder="请输入商品运费模板" />
            </el-form-item>

            <el-form-item label="图片" prop="path">
                <el-upload
                    class="avatar-uploader"
                    :action="imageUploadUrl"
                    :headers="data.header"
                    :data="data.ossdata"
                    name="imgFile"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                  >
                    <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                  </el-upload>
            </el-form-item>

        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>

</template>

<script lang="ts" setup>
    import { reactive, ref,getCurrentInstance, ComponentInternalInstance  } from 'vue';
    import { type FormRules, type FormInstance, ElMessage, type UploadFile  } from 'element-plus';

    import { getToken } from '@/utils/auth';
    import { FormReq, productsResp } from '@/types/store/products';
    import { addProduct, getProductById, updateProduct } from '@/api/app/store/products';


    const { proxy } = getCurrentInstance() as ComponentInternalInstance;
    const { sys_yes_no } = proxy!.useDict('sys_yes_no');

    //图片上传地址
    const imageUploadUrl =ref(import.meta.env.VITE_APP_BASE_API+'/oss/uploadImg');
    const token=getToken();
    //配置请求头的令牌
    const header={
        header: {
            'Authorization': token
        }
    } ;

    //自己的定义额外参数
    const data = reactive({
        header: {
            'Authorization': token
        },
        ossdata: {
            fatherPath:'images'
        }
    });
    const open = ref(false);
    //得到数据表单form样式对象
    const formRef = ref<FormInstance>();
    //声明子组件的自定义事件 https://cn.vuejs.org/api/sfc-script-setup.html#defineprops-defineemits
    const emit = defineEmits(['refreshDataList']);
    // 定义表单对象
const form = ref<FormReq>({
    productId: undefined,
    superId: 0,
    categoryId: 0,
    productName: '',
    saleNot: 0,
    imageUrl: '',
    isDiscount: '',
    productPrice: 0,
    inventory: 0,
    detail: '',
    isCreditsExchange: 0,
    freeNot: 0,
    templateId: 0,
});
    // 表单验证
const rules = reactive<FormRules>({
    productName: [
        { required: true, message: '该值不能为空', trigger: 'blur' }
    ],
    superId: [
        { required: true, message: '该值不能为空', trigger: 'blur' }
    ],
    productPrice: [
        { required: true, message: '该值不能为空', trigger: 'blur' },
    ]
});
//对话框保存按钮
const submitForm = () => {
    formRef.value.validate((valid: boolean) => {
        //验证不成功
       	if (!valid) {
       		return false;
       	}

        //修改
        if(form.value.productId!== undefined){
            updateProduct(form.value).then(resp=>{
                ElMessage.success({
                    message: '修改成功',
                    duration: 500,
                    onClose: () => {
                        //关闭弹窗
                        open.value = false;
                        //调用重新查询数据操作
                        emit('refreshDataList');
                    }
                });

            });
        }else{
            //新增
            addProduct(form.value).then(resp=>{
                ElMessage.success({
                    message: '新增成功',
                    duration: 500,
                    onClose: () => {
                        //关闭弹窗
                        open.value = false;
                        //调用重新查询数据操作
                        emit('refreshDataList');
                    }
                });

            });
        }

    });

};

//对话框取消按钮
const cancel = () => {
    open.value = false;
    resetFrom();
};
// 重置表单
const resetFrom = () => {
    // 清空表单样式
    if (formRef.value){
        formRef.value.resetFields();
    }
    // 重置值
    form.value = {
        productId: undefined,
        superId: 0,
        categoryId: 0,
        productName: '',
        saleNot: 0,
        imageUrl: '',
        isDiscount: '',
        productPrice: 0,
        inventory: 0,
        detail: '',
        isCreditsExchange: 0,
        freeNot: 0,
        templateId: 0,
    };
};
//判断如果是修改操作，就要查询数据库，还原数据,要暴露出去
const init = (productId?: number|undefined) => {
    // 重置表单数据
    resetFrom();
    if (productId) {
        // 查询数据
        getProductById(productId).then(resp => {

            form.value=resp.data ;
        });
    }
    open.value = true;
};

// 上传图片时检查
function  beforeAvatarUpload(file) {
    console.log(file);
    //允许的图片类型
    const imgType = (file.type === 'image/jpeg') || (file.type === 'image/png') || (file.type === 'image/gif');
    //文件大小3M
    const imgLimit= (file.size / 1024 / 1024) < 3;
    if (!imgType) {
        ElMessage.error("只允许jpg、png、gif格式的图片");
        return false;
    }
    if (!imgLimit) {
        ElMessage.error("上传的图片大小不能超过3MB");
        return false;
    }

    return true;
}

/** 上传图片 */
function handleAvatarSuccess(res, file)  {
    console.log(res);
    form.value.imageUrl=res.data;
};

//https://cn.vuejs.org/api/sfc-script-setup.html#defineexpose
defineExpose({
   	init
});
</script>

<style>
</style>
